package org.linlinjava.litemall.wx.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallAddress;
import org.linlinjava.litemall.db.domain.LitemallRegion;
import org.linlinjava.litemall.db.service.LitemallAddressService;
import org.linlinjava.litemall.db.service.LitemallRegionService;
import org.linlinjava.litemall.wx.annotation.LogAnno;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.GetRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

import static org.linlinjava.litemall.wx.util.WxResponseCode.*;

@RestController
@RequestMapping("/wx/address")
@Validated
public class WxAddressController extends GetRegionService {

    @Autowired
	private LitemallAddressService addressService;

    @Autowired
	private LitemallRegionService regionService;

    @GetMapping("list")
	@LogAnno
	@ApiOperation("用户收货地址列表")
	public Object list(@LoginUser Integer userId) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}
		List<LitemallAddress> addressList = addressService.list(Wrappers.lambdaQuery(LitemallAddress.class)
				.eq(LitemallAddress::getDeleted,0)
				.eq(LitemallAddress::getUserId,userId));
		return ResponseUtil.okList(addressList);
	}

    @GetMapping("detail")
	@LogAnno
	@ApiOperation("收货地址详情")
	public Object detail(@LoginUser Integer userId, @NotNull Integer id) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}

		LitemallAddress address = addressService.query(userId, id);
		address.setTel(address.getTel().substring(1));
		if (address == null) {
			return ResponseUtil.badArgumentValue();
		}
		return ResponseUtil.ok(address);
	}

    private Object validate(LitemallAddress address) {
		String name = address.getName();
		if (StringUtils.isEmpty(name)) {
			return ResponseUtil.badArgument(NAME_NULL, "param: name is null");
		}

		String surname = address.getSurname();
		if (StringUtils.isEmpty(surname)) {
			return ResponseUtil.badArgument(SURNAME_NULL, "param: surname is null");
		}

		// 测试收货手机号码是否正确
		/*String mobile = address.getTel();
		if (!StringUtils.isEmpty(mobile) && !RegexUtil.isMobileExact(mobile)) {
			return ResponseUtil.badArgument(MOBILE_FORMARTTER_ERROR, "param: mobile fomartter is error");
		}*/

		String province = address.getProvince();
		if (StringUtils.isEmpty(province)) {
			return ResponseUtil.badArgument(PROVINCE_NULL, "param: province is null");
		}

		String city = address.getCity();
		if (StringUtils.isEmpty(city)) {
			return ResponseUtil.badArgument(CITY_NULL, "param: city is null");
		}


		String country = address.getCountry();
		if (StringUtils.isEmpty(country)) {
			return ResponseUtil.badArgument(COUNTRY_NULL, "param: country is null");
		}

//		String county = address.getCounty();
//		if (StringUtils.isEmpty(county)) {
//			return ResponseUtil.badArgument(401, "param: county is null");
//		}


		/*String areaCode = address.getAreaCode();
		if (StringUtils.isEmpty(areaCode)) {
			return ResponseUtil.badArgument(401, "param: areaCode is null");
		}*/

		String detailedAddress = address.getAddressDetail();
		if (StringUtils.isEmpty(detailedAddress)) {
			return ResponseUtil.badArgument(DETAILADDRESS_NULL, "param: detailedAddress is null");
		}

		Boolean isDefault = address.getIsDefault();
		if (isDefault == null) {
			return ResponseUtil.badArgument(ISDEFAULT_NULL, "param: isDefault is null");
		}

		if(address.getLatitude() == null || address.getLongitude() == null){
			return ResponseUtil.badArgument(LATITUDE_OR_LONGITUDE, "param: latitude or longitude is null");
		}
		return null;
	}

    @PostMapping("save")
	@LogAnno
	@ApiOperation("添加或更新收货地址")
	public Object save(@LoginUser Integer userId, @RequestBody LitemallAddress address) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}
		address.setPostalCode(address.getPostalCode().replaceAll(" ", ""));
		Object error = validate(address);
		if (error != null) {
			return error;
		}

		if (address.getIsDefault()) {
			// 重置其他收获地址的默认选项
			addressService.update(Wrappers.lambdaUpdate(LitemallAddress.class)
					.ge(LitemallAddress::getUserId,userId)
					.set(LitemallAddress::getIsDefault,false)
			);
			//addressService.resetDefault(userId);
		}
		address.setUserId(userId);
		address.setDeleted(false);
		return addressService.saveOrUpdate(address)?ResponseUtil.ok(address.getId()):ResponseUtil.updatedDataFailed();
	}

    @PostMapping("delete")
	@LogAnno
	@ApiOperation("删除收货地址")
	public Object delete(@LoginUser Integer userId, @RequestBody LitemallAddress address) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}
		Integer id = address.getId();
		if (id == null) {
			return ResponseUtil.badArgument();
		}

		addressService.delete(id);
		return ResponseUtil.ok();
	}

    @GetMapping("/clist")
	@LogAnno
	@ApiOperation("国家列表")
	public Object clist() {
		List<LitemallRegion> countryList = regionService.queryByPid(0);
		return ResponseUtil.okList(countryList);
	}

    @GetMapping("/slist")
	@LogAnno
	@ApiOperation("子地区列表（省/市）")
	public Object plist(@RequestParam(value = "id") Integer id, @NotNull Integer type) {
		if(id == null){
			//获取所有省份
			return ResponseUtil.okList(regionService.queryByType(type.byteValue()));
		}else{
			List<LitemallRegion> regionList = regionService.queryByPid(id);
			return ResponseUtil.okList(regionList);
		}
	}
}
